from django.shortcuts import render

from django.core.paginator import Paginator
from rest_framework.views import APIView
from rest_framework.response import Response
from users.views import Show_Address
from users.models import *
from goods.ser import *
from users.ser import Address_Ser
from utils.comm import get_redis
# Create your views here.

#读取首页三级分类
# 读取首页三级分类

class Home(APIView):
    def get(self, request):
        # 读取一级
        cates = Category.objects.filter(parent_id__isnull=True).all()
        list = []
        for i in cates:
            dict = {}
            dict['id'] = i.id
            dict['name'] = i.name
            # 读取二级
            two = i.subs.all()
            twolist = []
            # 遍历二级获取三级
            for j in two:
                twodict = {}
                twodict['id'] = j.id
                twodict['name'] = j.name
                three = j.subs.all()
                ser = CateSer(three, many=True)
                twodict['subs'] = ser.data
                twolist.append(twodict)

            dict['subs'] = twolist
            list.append(dict)
        # 查询一级分类，一级下面的二级，一级下面的三级，一级下面所有的商品
        categoods = []
        for j in cates:
            dict = {}
            dict['id'] = j.id
            dict['name'] = j.name
            dict['pic'] = str(j.pic)
            two = j.subs.all()
            twoser = CateSer(two, many=True)
            dict['two'] = twoser.data
            # 获取三级
            three = Category.objects.filter(top_parent=j.id, level=3).all()
            threeser = CateSer(three, many=True)
            dict['three'] = threeser.data
            # 获取商品,排序，新品按时间倒序排，价格，销量
            sorted = request.GET.get('sorted')
            topid = request.GET.get('topid')
            print(j.id)
            goods = Goods.objects.filter(category1_id=j.id, home_show=1).all()
            if sorted:
                if int(topid) == int(j.id):
                    goods = Goods.objects.filter(category1_id=j.id, home_show=1).order_by('-' + sorted).all()

            gser = GoodsSer(goods, many=True)
            dict['goods'] = gser.data
            categoods.append(dict)
        return Response({"code": 200, 'catelist': list, 'categoods': categoods})

class Goods_API(APIView):
    def get(self,request):
        id = request.GET.get('id')
        g = Goods.objects.filter(id=id).first()
        ser = GoodsSer(g)
        return Response({"code":200,"list":ser.data})

class Cart_API(APIView):
    def post(self, request):
        userid = request.data.get('user')
        goodsid = request.data.get('goods')
        number = request.data.get('number')
        cat = Cart.objects.filter(user_id=userid, goods_id=goodsid).first()
        if cat:
            cat.number += number
            cat.save()
            return Response({"code": 200})
        else:
            ser = CartSer(data=request.data)
            if ser.is_valid():
                ser.save()
                return Response({"code": 200})
            else:
                print(ser.errors)
                return Response({"code":10010})

    def get(self,request):
        user = request.GET.get('user')
        selected_all = request.GET.get('selected_all')
        c = Cart.objects.filter(user_id=user).all()
        ser = ssCartSer(c,many=True)
        cont = 0
        cont_all = 0
        money = 0
        for i in c:
            cont_all += i.number
            if i.is_checked == False:
                selected_all = False
            else:
                selected_all = True
                cont += i.number
                goods = Goods.objects.filter(id=i.goods_id).first()
                money += i.number * float(goods.price)
        return Response({"list":ser.data,'selected_all':selected_all,'cont':cont,'cont_all':cont_all,'money':money})

    def put(self,request):
        user = request.GET.get('user')
        id = request.GET.get('id')
        c = Cart.objects.filter(user_id=user,goods_id=id).first()
        if c.is_checked == True:
            c.is_checked = False
            c.save()
            return Response({"code":200})
        else:
            c.is_checked = True
            c.save()
            return Response({"code": 200})

class Jia(APIView):
    def post(self,request):
        user = request.data.get('user')
        id = request.data.get('id')
        t = request.data.get('t')
        c = Cart.objects.filter(user_id=user,id=id).first()
        if t == 1:
            c.number -= 1
            c.save()
        elif t == 2:
            c.number += 1
            c.save()
        return Response({"code":200})


class Show_Cart(APIView):
    def put(self,request):
        selected_all = request.GET.get('selected_all')
        user = request.GET.get('user')
        if selected_all=='true':
            Cart.objects.filter(user_id=user).update(is_checked=True)
        else:
            Cart.objects.filter(user_id=user).update(is_checked=False)
        return Response({"code":200})

    def get(self,request):
        user = request.GET.get('user')
        c = Cart.objects.filter(user_id=user).all()
        ser = ssCartSer(c,many=True)
        for i in c:
            if i.is_checked == True:
                return Response({"code":200,"goods":ser.data})

class show_Goosd(APIView):
    def get(self,request):
        user = request.GET.get('user')
        c = Cart.objects.filter(user_id=user,is_checked=True).all()
        ser = ssCartSer(c,many=True)
        num = 0
        zongjia = 0
        for i in ser.data:
            num += i['number']
            zongjia += float(i['goods']['price']) * i['number']
        return Response({"code": 200, "goods": ser.data,"zongjia":zongjia,"num":num})

import datetime
import random
from  django.db  import transaction

class OrderInfo_API(APIView):
    # @transaction.atomic
    def post(self,request):
        user = request.data.get('user')
        pay_money = request.data.get('pay_money')
        usernameid = request.data.get('usernameid')
        # 根据userid查询购物车中已经选中的记录
        car = Cart.objects.filter(user_id=user, is_checked=True).all()
        carser = ssCartSer(car,many=True)
        yuan = 0
 # 构造订单表
        #获取总金额
        for i in carser.data:
            yuan += i['number'] * float(i['goods']['price'])
        #生产订单号
        order_no = datetime.datetime.strftime(datetime.datetime.now(),'%Y%M%D%H%M%S')+str(user)+str(random.randint(10000,99999))
        # 获取地址
        address = Address.objects.filter(id=usernameid).first()

        addser = Address_Ser(address)
        #构造地址字段
        adde = addser.data
        addes = str(adde['province']) + ' '+str(adde['city']) + ' ' + str(adde['area']) + ' ' + str(adde['address']) + str(adde['receive']) + ' ' + str(adde['mobile'])
        OrderInfo_data = {'order_no':order_no,'user':user,'address':addes,'total_amount':yuan,'pay_method':pay_money}
        ordser = OrderInfoSer(data=OrderInfo_data)
        if ordser.is_valid():
            ordser.save()
            #构造构造订单详情表
            for i in carser.data:
                OrderDetaildata = {'order':order_no,'goods':i['goods']['id'],'goodsname':i['goods']['name'],
                                   'images':i['goods']['pic'],'count':i['number'],'price':i['goods']['price'],'user':user}
                OrderDetailser1 = OrderDetailser(data=OrderDetaildata)
                if OrderDetailser1.is_valid():
                    OrderDetailser1.save()

        Cart.objects.filter(user_id=user,is_checked=True).delete()
        return Response({"code":200,'order_no': order_no, 'tmoney': yuan})